﻿using System;
using System.IO;
using System.Text;
using JavaScriptSupport;

namespace ShrinkWrap.Minifier
{
    public class JavascriptMinifier : IMinifier
    {
        /// <summary>
        /// Minify the input using a C# translation of jsmin
        /// </summary>
        /// <param name="input">Js string for minification</param>
        /// <returns>Minified version of the input</returns>
        public String Minify( String input )
        {
            // Build a stream from the input string
            Encoding encoding = Encoding.UTF8;
            byte[] inputBytes = encoding.GetBytes(input);
            MemoryStream inputStream = new MemoryStream(inputBytes);
            
            using( StreamReader reader = new StreamReader(inputStream) )
            {
                // Build a stream to hold the minified output
                MemoryStream outputStream = new MemoryStream();
                using (StreamWriter outputWriter = new StreamWriter(outputStream, encoding))
                {
                    // Minify the input
                    JavaScriptMinifier minifier = new JavaScriptMinifier();
                    minifier.Minify(reader, outputWriter);

                    // Retrieve the result from the outputStream
                    outputWriter.Flush();
                    outputStream.Flush();
                    outputStream.Position = 0;
                    StreamReader outputReader = new StreamReader(outputStream);
                    String output = outputReader.ReadToEnd();

                    return output;
                }
            }
        }
    }
}
